import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/common/index.dart';

import 'login_state.dart';

class PhoneArea extends StatefulWidget {
  const PhoneArea({Key? key}) : super(key: key);

  @override
  State<PhoneArea> createState() => _PhoneAreaState();
}

class _PhoneAreaState extends State<PhoneArea> {
  late ScrollController _scrollController; // 滚动控制器
  final double _cellHeight = 50; // item的高度
  final double _groupHeight = 34.0; // 组头高度
  final Map<String, double> _groupOffsetMap = {};

  List<Map<String, dynamic>> _data = []; // 国家数据List

  @override
  void initState() {
    super.initState();
    _data = _countryData(); // 获取所有国家数据

    _scrollController = ScrollController(); // 初始化滚动控制器

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _calculateGroupOffsets();
    });
  }

  // 计算每组的偏移量，设置到 _groupOffsetMap 中
  void _calculateGroupOffsets() {
    double groupOffset = 0.0; // 初始化偏移量为 0，确保计算从列表顶部开始

    for (int i = 0; i < _data.length; i++) {
      if (i == 0) {
        // 如果是第一个元素，直接将偏移量添加到字母组
        _groupOffsetMap[_data[i]["initialsy"]] = groupOffset;
      } else if (_data[i]["initialsy"] == _data[i - 1]["initialsy"]) {
        // 如果当前项与前一个项属于同一组，则只累加 item 的高度
        groupOffset += _cellHeight;
      } else {
        // 如果是新的一组，则累加组头高度 + 当前项高度
        groupOffset += _groupHeight;
        groupOffset += _cellHeight; // 累加当前项的高度
        _groupOffsetMap[_data[i]["initialsy"]] = groupOffset;
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    _data.clear();
    _groupOffsetMap.clear();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarColor: Colors.transparent,
      ),
    );
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '选择国家和地区',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
      ),
      body: _countryOrIndexBar(),
    );
  }

  // 各个国家地区和索引条
  Widget _countryOrIndexBar() {
    return Stack(
      children: [
        ListView.builder(
          controller: _scrollController, // 控制器
          itemCount: _data.length,
          itemBuilder: (context, index) {
            bool isShowT = index > 0 &&
                _data[index]["initialsy"] == _data[index - 1]["initialsy"];
            return InkWell(
              onTap: () {},
              child: _CountryCell(
                country: "${_data[index]["country"]}",
                code: "${_data[index]["code"]}",
                groupTitle: isShowT ? null : _data[index]["initialsy"],
              ),
            );
          },
        ),
        IndexBar(
          indexBarCallBack: (String str) {
            if (_groupOffsetMap[str] != null) {
              _scrollController.animateTo(
                _groupOffsetMap[str]!,
                duration: const Duration(milliseconds: 350),
                curve: Curves.easeOut,
              );
            }
          },
        ),
      ],
    );
  }

  // 假数据
  List<Map<String, dynamic>> _countryData() {
    List<Map<String, dynamic>> list = [];
    // INDEX_WORDS.forEach((element) {
    //   for (int i = 0; i < 10; i++) {
    //     list.add(
    //         {"initialsy": element, "country": "$element中国", "code": "+86"});
    //   }
    // });
    areaData["data"].forEach((element) {
      list.add(
        {"initialsy": element['countryNameEn'].toString().substring(0,1), "country": element['countryNameZh'], "code": element['countryCode']},
      );
    });
    return list;
  }
}

// 国家列表项
class _CountryCell extends StatelessWidget {
  final String? country; // 名称
  final String? code; // 名称
  final String? groupTitle; // 组头标题

  const _CountryCell({super.key, this.groupTitle, this.country, this.code});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (groupTitle != null)
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.only(left: 16),
            height: 34,
            color: const Color(0xFFF5F6F8),
            child: Text(
              groupTitle!,
              style: const TextStyle(color: Color(0xFF999999)),
            ),
          ),
        Container(
          color: Colors.white,
          child: Column(
            children: [
              InkWell(
                onTap: () {
                 Get.back(result: code);
                },
                child: Container(
                  alignment: Alignment.centerLeft,
                  height: 49.5,
                  padding: const EdgeInsets.only(left: 16),
                  child: Text(
                    "$country $code",
                    style: const TextStyle(fontSize: 16, color: Colors.black),
                  ),
                ),
              ),
              const Divider(height: 0.5, color: Color(0xFFCCCCCC)),
            ],
          ),
        ),
      ],
    );
  }
}

/*
 * 索引条
 */
class IndexBar extends StatefulWidget {
  final void Function(String str)? indexBarCallBack;

  IndexBar({this.indexBarCallBack});

  @override
  State<IndexBar> createState() => _IndexBarState();
}

class _IndexBarState extends State<IndexBar> {
  Color _backColor = const Color.fromRGBO(1, 1, 1, 0.0); //背景色
  Color _textColor = Color(0xFF999999);
  double _indicatorY = 0.0;
  bool _indicatorHidden = true;
  String _indicatorText = 'A';
  int _index = 0;

  @override
  Widget build(BuildContext context) {
    final List<Widget> words = []; //字母索引
    for (int i = 0; i < INDEX_WORDS.length; i++) {
      words.add(
        Expanded(
          child: Text(
            INDEX_WORDS[i],
            style: TextStyle(fontSize: 12, color: _textColor),
          ),
        ),
      );
    }

    return Positioned(
      right: 13,
      top: 113,
      height: 408,
      width: 110,
      child: Row(
        children: [
          //指示器
          Container(
            alignment: Alignment(0, _indicatorY),
            width: 90,
            // color: Colors.red,
            child: _indicatorHidden
                ? null
                : Stack(
              alignment: const Alignment(-0.2, 0),
              children: [
                // Image(
                //     image: AssetImage("assets/images/bubble.png"),
                //     width: 55),
                Container(
                  width: 55,
                  height: 55,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color(0xFF333333),
                      borderRadius: BorderRadius.circular(8)),
                  child: Text(
                    _indicatorText,
                    style: TextStyle(fontSize: 18, color: Colors.white),
                  ),
                )
              ],
            ),
          ),
          //索引
          GestureDetector(
            onVerticalDragDown: (DragDownDetails details) {
              int index = getIndexItem(context, details.globalPosition);
              //防止多次触发
              if (_index == index) return;
              _index = index;
              widget.indexBarCallBack!(INDEX_WORDS[index]);
              setState(() {
                _backColor = Colors.transparent; //设置背景颜色
                _textColor = Colors.black; //文字显示颜色
                _indicatorY =
                    2.28 / INDEX_WORDS.length * index - 1.14; //改变坐标 Y值
                _indicatorText = INDEX_WORDS[index]; //获取对应的字母
                _indicatorHidden = false; //是否隐藏指示器
              });
            },
            onVerticalDragEnd: (DragEndDetails details) {
              setState(() {
                _backColor = const Color.fromRGBO(1, 1, 1, 0.0);
                _textColor = Colors.black;
                _indicatorHidden = true;
              });
            },
            onVerticalDragUpdate: (DragUpdateDetails details) {
              int index = getIndexItem(context, details.globalPosition);
              //防止多次触发
              if (_index == index) return;
              _index = index;
              widget.indexBarCallBack!(INDEX_WORDS[index]);
              setState(() {
                _indicatorY = 2.28 / INDEX_WORDS.length * index - 1.14;
                _indicatorText = INDEX_WORDS[index];
                _indicatorHidden = false;
              });
            },
            child: Container(
              width: 20,
              color: _backColor,
              child: Column(
                children: words,
              ),
            ),
          )
        ],
      ),
    );
  }
}

int getIndexItem(BuildContext context, Offset globalPosition) {
  //拿到当前盒子
  RenderBox box = context.findRenderObject() as RenderBox;
  //拿到y值，当前位置到部件原点(部件左上角)的距离(x,y)
  var y = box.globalToLocal(globalPosition).dy;
  //算出字符高度
  var itemHeight = MediaQuery.of(context).size.height / 2 / INDEX_WORDS.length;
  int index =
      y ~/ itemHeight.clamp(0, INDEX_WORDS.length - 1); //~取整,设置取整范围clamp
  if (index > 25) {
    index = 25;
  }
  return index;
}

const INDEX_WORDS = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
];